﻿using System;
using NHibernate;
using TestBat.IModels.Domain;
using TestBat.IModels.Repositories;
using TestBat.Models.Domain;

namespace TestBat.Models.Repositories
{
    public class TraineeGroupRepository : Repository<ITraineeGroup, Guid>, ITraineeGroupRepository
    {
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session">The NHibernate-sessionfactory</param>
        public TraineeGroupRepository(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }

        public override ITraineeGroup GetByID(Guid traineeGroupID)
        {
            return Session.Get<TraineeGroup>(traineeGroupID);
        }

        // HACK: whole override is a hack because NHibernate's Session.Refresh() doesn't refresh collections (added and removed entities)
        public override void Refresh(ITraineeGroup o)
        {
            if (Session.Contains(o))
            { // entity is part of this session

                var id = Session.GetIdentifier(o);

                Session.Evict(o);
                //Session.Clear(); // HACK: the session still thinks it is dirty, so we clear it fully; not sure which side-effects this introduces

                Session.Load(o, id);
            }
            else
            { // entity is not part of this session
                try
                {
                    Session.Refresh(o); // try, if entity is detached
                }
                catch (UnresolvableObjectException)
                { // object is transient anyway
                    return;
                }
            }
        }
    }
}
